/**
 * 用户服务
 */
const axios = require('axios');
const logger = require('../utils/logger');

/**
 * 通过code获取微信用户openID
 * @param {string} code - 微信登录code
 * @returns {Promise} 包含openID的Promise
 */
async function getOpenIdByCode(code) {
  try {
    // 从环境变量获取小程序配置
    const appId = process.env.WECHAT_APP_ID;
    const appSecret = process.env.WECHAT_APP_SECRET;
    
    if (!appId || !appSecret) {
      logger.error('缺少微信小程序配置环境变量');
      throw new Error('未配置微信小程序信息');
    }
    
    // 请求微信API
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    const response = await axios.get(url);
    
    if (response.data.errcode) {
      logger.error('微信登录API错误', response.data);
      throw new Error(`微信登录失败: ${response.data.errmsg}`);
    }
    
    return {
      openid: response.data.openid,
      session_key: response.data.session_key,
      unionid: response.data.unionid
    };
  } catch (error) {
    logger.error('获取微信OpenID失败', {
      message: error.message,
      stack: error.stack
    });
    throw error;
  }
}

/**
 * 保存或更新用户信息
 * @param {object} pool - 数据库连接池
 * @param {string} openId - 用户微信OpenID
 * @param {object} userInfo - 用户信息对象
 * @returns {Promise<object>} 用户信息
 */
async function saveUserInfo(pool, openId, userInfo) {
  const connection = await pool.getConnection();
  try {
    // 查询用户是否存在
    const [users] = await connection.query('SELECT * FROM users WHERE open_id = ?', [openId]);
    
    const currentTime = new Date();
    
    if (users.length > 0) {
      // 更新现有用户
      const userId = users[0].id;
      await connection.query(
        `UPDATE users SET 
         nick_name = ?, 
         avatar_url = ?, 
         gender = ?, 
         country = ?, 
         province = ?, 
         city = ?, 
         language = ?, 
         last_login = ?
         WHERE id = ?`,
        [
          userInfo.nickName,
          userInfo.avatarUrl,
          userInfo.gender,
          userInfo.country,
          userInfo.province,
          userInfo.city,
          userInfo.language,
          currentTime,
          userId
        ]
      );
      return { ...users[0], ...userInfo, id: userId, lastLogin: currentTime };
    } else {
      // 创建新用户
      const [result] = await connection.query(
        `INSERT INTO users 
         (open_id, nick_name, avatar_url, gender, country, province, city, language, last_login) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          openId,
          userInfo.nickName,
          userInfo.avatarUrl,
          userInfo.gender,
          userInfo.country,
          userInfo.province,
          userInfo.city,
          userInfo.language,
          currentTime
        ]
      );
      return { 
        id: result.insertId,
        open_id: openId,
        ...userInfo,
        lastLogin: currentTime
      };
    }
  } catch (error) {
    logger.error('保存/更新用户信息失败', {
      message: error.message,
      stack: error.stack
    });
    throw error;
  } finally {
    connection.release();
  }
}

/**
 * 保存诊断历史记录
 * @param {object} pool - 数据库连接池
 * @param {number} userId - 用户ID
 * @param {object} diagnosisRecord - 诊断记录对象
 * @returns {Promise<number>} 插入的记录ID
 */
async function saveDiagnosisRecord(pool, userId, diagnosisRecord) {
  const connection = await pool.getConnection();
  try {
    const [result] = await connection.query(
      `INSERT INTO diagnosis_history 
       (user_id, plant_name, latin_name, family, image_url, diagnosis_result, treatment, prevention_tips, growth_advice) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        userId,
        diagnosisRecord.plantName,
        diagnosisRecord.latinName || '',
        diagnosisRecord.family || '',
        diagnosisRecord.imageUrl || '',
        diagnosisRecord.diagnosisResult || '',
        diagnosisRecord.treatment || '',
        diagnosisRecord.preventionTips || '',
        diagnosisRecord.growthAdvice || ''
      ]
    );
    return result.insertId;
  } catch (error) {
    logger.error('保存诊断历史记录失败', {
      message: error.message,
      stack: error.stack
    });
    throw error;
  } finally {
    connection.release();
  }
}

/**
 * 获取用户诊断历史记录
 * @param {object} pool - 数据库连接池
 * @param {number} userId - 用户ID
 * @param {number} limit - 限制返回数量
 * @param {number} offset - 偏移量
 * @returns {Promise<Array>} 历史记录数组
 */
async function getUserDiagnosisHistory(pool, userId, limit = 20, offset = 0) {
  const connection = await pool.getConnection();
  try {
    const [records] = await connection.query(
      `SELECT * FROM diagnosis_history 
       WHERE user_id = ? 
       ORDER BY diagnosis_time DESC 
       LIMIT ? OFFSET ?`,
      [userId, limit, offset]
    );
    return records;
  } catch (error) {
    logger.error('获取用户诊断历史记录失败', {
      message: error.message,
      stack: error.stack
    });
    throw error;
  } finally {
    connection.release();
  }
}

module.exports = {
  getOpenIdByCode,
  saveUserInfo,
  saveDiagnosisRecord,
  getUserDiagnosisHistory
};
